# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date:
# @Last Modified by: CPS
# @Last Modified time: 2021-04-12 03:25:48.660601
# @file_path "D:\CPS\IDE\JS_SublmieText\Data\Packages\CPS"
# @Filename "main.py"
# @Description: 功能描述
#


import sublime
import sublime_plugin
import os
import re

tmp = ""
info=""
tar=None
tmp_edit=None

if int(sublime.version()) < 3176:
    raise ImportWarning("本插件不支持当前版本，请使用大于等于3176的sublime Text")

else:
    from .core.utils import env
    from .core.utils import node
    from .core.utils import tools

    from .core import settings
    from .core.update_channel import init as update_channel_init
    from .core.update_channel import update_channel as update_channel_main

    from .core import beautify
    from .core.file_header import set_tmpl_path,get_header_info,get_tmpl_file,replace_tmpl_info
    
    # from . import comments

    env.set_plugin_name('CPS') # 设置当前插件名称

    # 当插件加载完成后执行
    def plugin_loaded():
        def plugin_loaded_async():
            settings.add_listener(env.get_plugin_name())
            update_channel_init()
            set_tmpl_path(env.get_plugin_name())

        # 在另一个进程执行该函数( 这样不会阻塞窗口的初始化，造成载入文件卡顿 )
        sublime.set_timeout_async(plugin_loaded_async)


    # 测试函数
    # 默认快捷键 ["alt+t"]
    class TesttTestCommand(sublime_plugin.TextCommand):
        def run(self,edit):
            view = self.view

            c = sublime.active_window()
            # print(dir(c))
            # print(c.window_id)
            c.show_quick_panel(['1','2'],self.select)
        def select(self,index):
            print('当前选择： ',index)


    # 重建当前目录的ctags文件
    def TesttRebuildCtagsFilesCommand(filepath=None):
        try:
            _window = sublime.active_window()
            _env = _window.extract_variables()

            if not 'file_path' in _env: return False

            params={"dirs":[],"files": []}
            folders_list = _window.folders()
            currt_file_path = os.path.abspath(_env['file_path'])
            folders_list_len = len(folders_list)

            for index,each_folder in enumerate(folders_list):
                if currt_file_path.find(each_folder) > -1:
                    params['dirs'].append(folders_list[index])
                    _window.run_command('rebuild_tags',params)

        except Exception as e:
            print('重建.ctags文件失败，请确保插件安装正确')
            print(e)

    #每次打开文件都会触发这个事件
    class ExecEventListener(sublime_plugin.EventListener):
        def on_pre_save(self,view):
            SETTINGS = settings.get_settings()
            if SETTINGS.get('format_on_save',False):
                sublime.active_window().run_command('testt_beautify_currt_file')

            # 优化 应该放到保存文件后触发异步
            if SETTINGS.get('rebuild_ctags_file_on_save',False):
                sublime.set_timeout_async(TesttRebuildCtagsFilesCommand,0)

    # 关联离线的 channel 文件到配置
    # 默认快捷键 ["alt+u"]
    class TesttUpdateChannelCommand(sublime_plugin.TextCommand):
        def run(self,edit):
            update_channel_main()


    # 打开当前文件夹的文件夹
    # 默认快捷键 ["alt+e"]
    class TesttOpenFileFloderCommand(sublime_plugin.TextCommand):
        def run(self, edit):
            #调用当前激活的窗口来执行 run_command命令(无法使用 self.view 调用 run_command)
            (fdir, fname) = os.path.split(self.view.file_name())
            sublime.active_window().run_command("open_dir", {"dir": fdir})



    # 格式化当前文件[支持格式： vue/js/ts/pug/stylus/css]
    class TesttBeautifyCurrtFileCommand(sublime_plugin.TextCommand):
        def run(self, edit, syntax=None):
            # 异步格式化文件，不卡主程序执行
            sublime.set_timeout_async(self.beautify(edit,syntax),0)

        def beautify(self,edit,syntax):
            # edit = TesttBeautifyCurrtFileCommand.edit
            # syntax = TesttBeautifyCurrtFileCommand.syntax
            _settings = settings.get_settings()

            # 当前文件内容转换成字符串
            region = sublime.Region(0, self.view.size())
            buffer_str = self.view.substr(region)

            # 获取当前文件语法
            if not syntax:
                syntax = tools.check_stynax(self.view.file_name()) or tools.check_stynax(self.view.settings().get('syntax'))

            if not syntax: return False

            # 获取当前鼠标位置
            cursor_offset = self.view.sel()[0].a

            # 获取当前配置
            options = settings.get_options(syntax)

            # 传送数据
            res = beautify.beautifyStr(buffer_str,syntax,cursor_offset,options)

            if res:
                # 替换新数据到当前文件
                self.view.replace(edit, region, res['formatted'])
                if _settings.get("show_view_at_center_when_format",False) :self.view.show_at_center(res['cursorOffset'])
                if int(res['cursorOffset']) > 0: sublime.Region((res['cursorOffset'],res['cursorOffset']))

                print('格式化成功:',syntax)


    # 格式化当前视图
    class TesttBeautifySelectRegionCommand(sublime_plugin.TextCommand):
        def run(self, edit, syntax=None):
            # 检测选区
            if self.view.sel()[0].empty() : return print('当前没有任何文件')

            # 检测语法
            if not syntax : return False

            # 当前文件第一个选区
            region = self.view.sel()[0]
            buffer_str = self.view.substr(region)

            # 获取当前鼠标位置
            cursor_offset = self.view.sel()[0].a

            # 获取当前配置
            options = settings.get_options(syntax)

            # html 转换成pug
            res = beautify.beautifyStr(buffer_str,syntax, cursor_offset, options, False)

            if syntax == 'html2pug':
                syntax = 'pug'
                options = settings.get_options(syntax)
                res = beautify.beautifyStr(res['formatted'],syntax,cursor_offset,options,False)

            if res and 'formatted' in res:
                # 替换新数据到当前文件
                self.view.replace(edit, region, res['formatted'])
                self.view.show_at_center(res['cursorOffset'])

                if int(res['cursorOffset']) > 0: sublime.Region((res['cursorOffset'],res['cursorOffset']))
                print('格式化成功:',os.path.basename(self.view.file_name()))


    # 设置语法
    class TesttSetSyntaxCommand(sublime_plugin.TextCommand):
        def run(self,edit,syntax):
            syntaxDict = {
              "html":"Packages/HTML/HTML.sublime-syntax",
              "vue":"Packages/Vue Syntax Highlight/Vue Component.sublime-syntax",
              "js":"Packages/JavaScriptNext - ES6 Syntax/JavaScriptNext.tmLanguage"
            }
            if syntax : self.view.set_syntax_file(syntaxDict[syntax])
